﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;


using P2PTransmit.Modal;
using P2PTransmit.Modal.Protocol;

namespace P2PTransmit.ViewModal.Service
{
    public delegate void FindConnectionEventHandler(string connectionName);
    public class ConnectionService : ProtocolService<Connection>
    {
        HashSet<Connection>                                 Table;
        public event FindConnectionEventHandler             OnFindConnection;
        public event FindConnectionEventHandler             OnConnectionNameChanged;

        public ConnectionService(int port) : base( port )
        {
            Table = new HashSet<Connection>();
            base.OnReceive += Filter;
        }

        private void Validate(Connection conn)
        {
            if(Table.Add(conn))//没有被发现的连接
            {
                Pool.Add( conn );
                OnFindConnection?.Invoke( conn.MachineName );
            }
            else
            {
                //修改信息
                OnConnectionNameChanged?.Invoke( conn.MachineName );
                var find = ( from e in Pool where e.Equals( conn ) select e ).Single();
                if ( conn.MachineIPAddress != find.MachineIPAddress )
                    find.MachineIPAddress = conn.MachineIPAddress;
                if ( conn.MachineName != find.MachineName )
                    find.MachineName = conn.MachineName;               
            }            
        }
        private void Filter(string json, IPEndPoint source)
        {
            var protocol = Deserialize<EchoProtocol>( json );
            if(protocol.SourcesMacAddress != ServiceManager.LocalMacAddress)
            {
                Validate( protocol.Connection );
            }
            if ( !protocol.Echo )
            {
                FindComputer( true );
            }
        }

        public void FindComputer(bool feedback = false)
        {
            var Protocol = new EchoProtocol()
            {
                Echo = feedback
            };
            Protocol.Connection = new Connection()
            {
                MachineIPAddress = ServiceManager.LocalIPAddress.ToString(),
                MachineMacAddress = ServiceManager.LocalMacAddress,
                MachineName = ServiceManager.LocalMachineName
            };
            Protocol.SourcesMacAddress = ServiceManager.LocalMacAddress;
            var json = Serialize( Protocol );
            base.Send( json );
        }

        public new void Dispose()
        {
            started = false;
            base.OnReceive -= Filter;
            base.Dispose();
        }
    }
}
